package com.excemly.library.service;

import com.excemly.library.entity.Book;
import com.excemly.library.entity.Borrow;
import com.excemly.library.entity.User;
import com.excemly.library.exceptions.ResourceNotFoundException;
import com.excemly.library.repository.BookRepository;
import com.excemly.library.repository.BorrowRepository;
import com.excemly.library.repository.UserRepository;
import jakarta.transaction.Transactional;
import org.springframework.stereotype.Service;
import java.time.LocalDate;
import java.util.List;

@Service
public class BorrowService {
    private final BorrowRepository borrowRepository;
    private final BookRepository bookRepository;
    private final UserRepository userRepository;

    public BorrowService(BorrowRepository borrowRepository, BookRepository bookRepository, UserRepository userRepository) {
        this.borrowRepository = borrowRepository;
        this.bookRepository = bookRepository;
        this.userRepository = userRepository;
    }

    // 获取用户借阅记录
    public List<Borrow> getUserBorrowRecords(Long userId) {
        User user = userRepository.findById(userId)
                .orElseThrow(() -> new ResourceNotFoundException("User not found"));
        return borrowRepository.findByUser(user);
    }

    // 借阅图书
    @Transactional
    public Borrow borrowBook(Long bookId, Long userId) {
        Book book = bookRepository.findById(bookId)
                .orElseThrow(() -> new ResourceNotFoundException("Book not found"));
        User user = userRepository.findById(userId)
                .orElseThrow(() -> new ResourceNotFoundException("User not found"));

        if (book.getAvailableCopies() <= 0) {
            throw new RuntimeException("Book is out of stock");
        }

        // 创建借阅记录
        Borrow borrow = new Borrow();
        borrow.setBook(book);
        borrow.setUser(user);
        borrow.setBorrowDate(LocalDate.now());
        borrow.setDueDate(LocalDate.now().plusDays(30)); // 30天借阅期

        // 更新库存
        book.setAvailableCopies(book.getAvailableCopies() - 1);
        bookRepository.save(book);

        return borrowRepository.save(borrow);
    }

    // 归还图书
    @Transactional
    public void returnBook(Long borrowId) {
        Borrow borrow = borrowRepository.findById(borrowId)
                .orElseThrow(() -> new ResourceNotFoundException("Borrow record not found"));

        if (borrow.getReturnDate() != null) {
            throw new RuntimeException("Book already returned");
        }

        // 更新归还日期
        borrow.setReturnDate(LocalDate.now());
        borrowRepository.save(borrow);

        // 更新库存
        Book book = borrow.getBook();
        book.setAvailableCopies(book.getAvailableCopies() + 1);
        bookRepository.save(book);
    }
}